import math


def haversine(lon1, lat1, lon2, lat2):
    # 将纬度和经度从度转换为弧度
    lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])

    # Haversine公式
    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

    # 地球的平均半径，单位：公里
    R = 6371.0
    distance = R * c

    return distance


if __name__ == "__main__":
    # 示例：计算北京(39.9042, 116.4074) 到上海(31.2304, 121.4737) 的距离
    distance = haversine(116.4074, 39.9042, 121.4737, 31.2304)
    print(f"北京到上海的距离是 {distance:.2f} 公里")

    distance = haversine(119.58969053989635, 34.193043012595204, 119.56094476357706, 34.18178508372696)
    print(f"两点的距离是 {distance:.2f} 公里")
    distance = haversine(119.58969053989635, 34.193043012595204, 119.61843631621564, 34.20429942480386)
    print(f"两点的距离是 {distance:.2f} 公里")

    distance = haversine(119.59347780852912, 34.19069534168553, 119.6042114034689, 34.19170852077673)
    print(f"两点的距离是 {distance:.2f} 公里")
